Summary of Common Methods of Obtaining File Extensions in PHP [Five Ways]

  • 2021-09-24 21:32:51
  • OfStack

This paper summarizes the common methods of obtaining file extension in PHP. Share it for your reference, as follows:

This is a pen test question I encountered when I applied for an internship:

Get the extension of 1 file in more than 5 ways.

Requirements: dir/upload. image. jpg, Find jpg or jpg,

You must use the processing function of PHP, and the method cannot be obviously repeated. It can be encapsulated as a function, such as get_ext1($file_name) , get_ext2($file_name)

The following are five methods that I summarized with reference to online materials, all of which are relatively simple, without saying much, and directly go to the code:

Method 1:


function getExt1($filename)
{
   $arr = explode('.',$filename);
   return array_pop($arr);;
}

Method 2:


function getExt2($filename)
{
   $ext = strrchr($filename,'.');
   return $ext;
}

Method 3:


function getExt3($filename)
{
   $pos = strrpos($filename, '.');
   $ext = substr($filename, $pos);
   return $ext;
}

Method 4:


function getExt4($filename)
{
   $arr = pathinfo($filename);
   $ext = $arr['extension'];
   return $ext;
}

Method 5:


function getExt5($filename)
{
   $str = strrev($filename);
   return strrev(strchr($str,'.',true));
}

For more readers interested in PHP related contents, please check the special topics of this site: "php File Operation Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Array (Array) Operation Skills Complete Book", "php String (string) Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: